package com.talkweb.osmharmony.tileprovider.modules;

import com.talkweb.osmharmony.tileprovider.IRegisterReceiver;
import ohos.event.commonevent.*;

public abstract class MapTileFileStorageProviderBase extends MapTileModuleProviderBase {

    private final IRegisterReceiver mRegisterReceiver;
    private MyBroadcastReceiver mBroadcastReceiver;

    public MapTileFileStorageProviderBase(final IRegisterReceiver pRegisterReceiver,
                                          final int pThreadPoolSize, final int pPendingQueueSize) {
        super(pThreadPoolSize, pPendingQueueSize);

        mRegisterReceiver = pRegisterReceiver;

        MatchingSkills matchingSkills = new MatchingSkills();
        matchingSkills.addEvent(CommonEventSupport.COMMON_EVENT_DISK_MOUNTED);
        matchingSkills.addEvent(CommonEventSupport.COMMON_EVENT_DISK_UNMOUNTED);
//        matchingSkills.addScheme("file"); //TODO 鸿蒙广播有待验证

        mBroadcastReceiver = new MyBroadcastReceiver(new CommonEventSubscribeInfo(matchingSkills));
        pRegisterReceiver.registerReceiver(mBroadcastReceiver);
    }

    @Override
    public void detach() {
        if (mBroadcastReceiver != null) {
            mRegisterReceiver.unregisterReceiver(mBroadcastReceiver);
            mBroadcastReceiver = null;
        }
        super.detach();
    }

    protected void onMediaMounted() {
        // Do nothing by default. Override to handle.
    }

    protected void onMediaUnmounted() {
        // Do nothing by default. Override to handle.
    }

    /**
     * This broadcast receiver will recheck the sd card when the mount/unmount messages happen
     */
    private class MyBroadcastReceiver extends CommonEventSubscriber {

        public MyBroadcastReceiver(CommonEventSubscribeInfo subscribeInfo) {
            super(subscribeInfo);
        }

        @Override
        public void onReceiveEvent(CommonEventData commonEventData) {
            final String action = commonEventData.getIntent().getAction();
            if (CommonEventSupport.COMMON_EVENT_DISK_MOUNTED.equals(action)) {
                onMediaMounted();
            } else if (CommonEventSupport.COMMON_EVENT_DISK_UNMOUNTED.equals(action)) {
                onMediaUnmounted();
            }

        }
    }
}
